import logging

import colorlog


def setup_logging():
    """配置日志输出，使用settings中的配置"""
    from src.config.settings import settings

    logger = logging.getLogger()

    # 设置日志级别
    log_level = getattr(logging, settings.LOG_LEVEL.upper())
    logger.setLevel(log_level)

    # 控制台彩色输出
    console_handler = colorlog.StreamHandler()
    console_handler.setFormatter(
        colorlog.ColoredFormatter(
            "%(log_color)s%(asctime)s - %(levelname)s - %(message)s",
            log_colors={
                "DEBUG": "cyan",
                "INFO": "green",
                "WARNING": "yellow",
                "ERROR": "red",
                "CRITICAL": "red,bg_white",
            },
        )
    )
    logger.addHandler(console_handler)

    # 文件输出
    if settings.LOG_FILE:
        import os
        from logging.handlers import RotatingFileHandler

        # 确保日志目录存在
        log_dir = os.path.dirname(settings.LOG_FILE)
        if log_dir and not os.path.exists(log_dir):
            os.makedirs(log_dir)

        file_handler = RotatingFileHandler(
            settings.LOG_FILE,
            maxBytes=settings.LOG_MAX_BYTES,
            backupCount=settings.LOG_BACKUP_COUNT,
            encoding=settings.LOG_ENCODING,
        )
        file_handler.setFormatter(logging.Formatter(settings.LOG_FORMAT))
        logger.addHandler(file_handler)
